package br.schindler.android.wallpaper.milkyway.pref;

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.EditTextPreference;
import android.text.InputType;
import android.util.AttributeSet;
import br.schindler.android.wallpaper.R;

public class NumberPickerPreference extends EditTextPreference {

	private Integer mInteger, mMax, mMin;
	
	private void setMaxMin(Context context) {
		TypedArray a = context.obtainStyledAttributes(R.styleable.cstm_edit_values);
		
		mMax = a.getInteger(R.styleable.cstm_edit_values_max_value,50);
		mMin = a.getInteger(R.styleable.cstm_edit_values_min_value, 0);
	
		a.recycle();

		getEditText()
				.setInputType(
						InputType.TYPE_CLASS_NUMBER
								| InputType.TYPE_NUMBER_FLAG_SIGNED);
	}

	public NumberPickerPreference(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		setMaxMin(context);	
	}

	public NumberPickerPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
		setMaxMin(context);
	}

	public NumberPickerPreference(Context context) {
		super(context);
		setMaxMin(context);
	}

	@Override
	public void setText(String text) {
		final boolean wasBlocking = shouldDisableDependents();
		Integer nValue = parseInteger(text);
		if ((nValue != null) && (nValue >= mMin) && (nValue <= mMax) )
		  mInteger = nValue;
		persistString(mInteger != null ? mInteger.toString() : "");
		final boolean isBlocking = shouldDisableDependents();
		if (isBlocking != wasBlocking)
			notifyDependencyChange(isBlocking);
	}

	@Override
	public String getText() {
		return mInteger != null ? mInteger.toString() : "";
	}

	private static Integer parseInteger(String text) {
		try {
			return Integer.parseInt(text);
		} catch (NumberFormatException e) {
			return null;
		}
	}
}